package com.project.core.config;

import org.noear.snack.core.exts.EnumWrap;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.convert.Converter;
import org.noear.solon.core.convert.ConverterFactory;
import org.noear.solon.core.exception.ConvertException;

@Component
@SuppressWarnings({"unchecked", "rawtypes"})
public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return new EnumTypeConverter<>(targetType);
    }

    public static class EnumTypeConverter<T extends Enum> implements Converter<String, T> {
        private final EnumWrap enumWrap;
        public EnumTypeConverter(Class<T> targetType){
            this.enumWrap = new EnumWrap(targetType);
        }

        @Override
        public T convert(String value) throws ConvertException {
            Enum<?> value2 = enumWrap.getCustom(value);
            if(value2 != null){
                return (T)value2;
            }
            return (T) enumWrap.get(value);
        }
    }
}